package com.adcc.soundalarm.service;

import com.adcc.soundalarm.common.Log;
import com.adcc.soundalarm.config.system.AlarmFactory;
import com.adcc.soundalarm.config.system.AppConfiguration;
import com.adcc.soundalarm.entity.LogInfo;
import com.adcc.soundalarm.listener.RequestMessageListener;
import com.adcc.utility.transport.DataListener;
import com.adcc.utility.transport.DataPacket;
import com.adcc.utility.transport.TranServer;
import com.adcc.utility.transport.udp.Transport;
import com.adcc.utility.transport.udp.UDPServer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import javafx.scene.control.Alert;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.util.List;
import java.util.Map;

public class RequestService {

    //构造方法私有化
    private RequestService() {
    }

    /**
     * 静态内部类
     */
    private static class LazyHolder {
        private static final RequestService INSTANCE = new RequestService();
    }

    /**
     * 单例方法
     */
    public synchronized static RequestService getInstance() {
        return LazyHolder.INSTANCE;
    }

    //请求消息监听器
    private RequestMessageListener requestMessageListener;

    private TranServer server = null;

    AlarmFactory alarmFactory = AppConfiguration.getInstance().getAlarmFactory();

    /**
     * 获取用户列表
     *
     * @return
     */
    public List<String> getUsers() throws Exception {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        List<String> userList = null;
        Map<String, Object> map = null;
        try {
            HttpGet httpGet = new HttpGet(alarmFactory.getUserUri());
            httpGet.setConfig(RequestConfig.custom().setSocketTimeout(60000).
                    setConnectTimeout(60000).build());
            httpClient = HttpClients.createDefault();
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                map = new ObjectMapper().readValue(response.getEntity().getContent(), Map.class);
                if (map != null && map.get("GWUser") != null) {
                    userList = (List) map.get("GWUser");
                }
            }
        } catch (Exception ex) {
            Log.error("getUsers() error! ", ex);
            throw new Exception(ex);
        } finally {
            close(response, httpClient);
        }
        return userList;
    }

    private void close(CloseableHttpResponse response, CloseableHttpClient client) {
        try {
            if (response != null) {
                response.close();
            }
        } catch (Exception ex) {
            Log.error("close response error", ex);
        } finally {
            response = null;
        }
        try {
            if (client != null) {
                client.close();
            }
        } catch (Exception ex) {
            Log.error("close client error", ex);
        } finally {
            client = null;
        }
    }

    /**
     *启动udp获取消息
     */
    public void start() {
        if (server == null) {
            createUdpServer();
        }else{
            //停止后重新启动
            server.stop();
            createUdpServer();
        }
    }

    /**
     * 创建udp服务端
     */
    public void createUdpServer() {
        if (!Strings.isNullOrEmpty(alarmFactory.getHost()) && alarmFactory.getPort() > 0) {
            if (alarmFactory.getTransport() == 2) {
                // 广播方式
                server = new UDPServer(alarmFactory.getPort());
            }else {
                server = new UDPServer(alarmFactory.getHost(), alarmFactory.getPort());
            }
            ((UDPServer) server).setTransport(Transport.values()[alarmFactory.getTransport()]);
            if (((UDPServer) server).getTransport() == Transport.MULTICAST) {
                ((UDPServer) server).getMulticastAddress().add(alarmFactory.getMultiAddress());//添加组播地址
            }
            server.setDataListener(new DataListener() {
                @Override
                public void onData(DataPacket dataPacket) {
                    try {
                        //结果集
                        LogInfo info = new ObjectMapper().readValue(dataPacket.getData(), LogInfo.class);
                        if (requestMessageListener != null) {
                            requestMessageListener.onMessage(info);
                        }
                    } catch (Exception ex) {
                        Log.error("dataPacket ObjectMapper().readValue error", ex);
                    }
                }
            });
            server.start();
        }
    }
    /**
     * 释放连接
     */
    public void dispose() {
        if (server != null) {
            server.stop();
        }
    }

    public void setRequestMessageListener(RequestMessageListener requestMessageListener) {
        this.requestMessageListener = requestMessageListener;
    }

}
